package com.loginregister.web.old; /**
 * @author wzm
 * @create 2023-05-04 11:12
 */


import com.loginregister.service.UserService;
import com.loginregister.service.impl.UserServiceImpl;
import com.loginregister.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //创建UserService对象
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //实现请求的处理和响应
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //2.获取页面参数(返回值是String类型 如果涉及 年龄 id 需要转换类型)
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //获取记住我选框
        String remember = request.getParameter("remember");

        User user = userService.login(new User(username, password));

        if (user != null){
            //查询成功
            if(user.getStatus() == 0){
                request.setAttribute("login_msg","用户被禁用");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return;
            }

            if ("1".equals(remember)){
                //勾选了记住我
                //将登录信息存储到cookie中
                Cookie uname = new Cookie("username",username);
                Cookie pwd = new Cookie("password",password);

                //七天存储时间
                uname.setMaxAge(60*60*24*7);
                pwd.setMaxAge(60*60*24*7);

                //通知浏览器保存
                response.addCookie(uname);
                response.addCookie(pwd);
            }

            //不存储登录信息
            //将登录后的用户存储起来 在整个网页中能够使用
            request.getSession().setAttribute("loginUser",user);
            response.sendRedirect(request.getContextPath()+"/index.jsp");

        }else{
            //失败
            //将错误信息存储
            request.setAttribute("login_msg","用户名或密码错误，请重试");

            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }


    }
}
